<template>
  <div class="app-container" style="height:100%;">
    <myTableSearch
      ref="myTableSearchRef"
      :isOperate="true"
      :operateWidth="180"
      :titleName="$route.meta.title"
      :queryFn="getList"
      :formData="formData"
      :tableLabel="tableLabel"
      :defaultExpandAll="true"
      @recombinationData="recombinationData"
      @successQuery="successQuery"
    >
      <template slot="tool">
        <div class="flex flex-x">
          <div class="fillBtn" @click="handleAdd" v-hasPermi="['system:dept:add']">
            <img src="@/assets/images/gzq/icon-add.png" alt="" />
            <span>新增数据</span>
          </div>
        </div>
      </template>

      <template slot="operate" slot-scope="scope">
        <div class="operateBtn flex">
          <div class="itemBtn " @click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">添加子机构</div>
          <div class="itemBtn ml-1" @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">编辑</div>
          <div class="itemBtn ml-1" @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</div>
        </div>
      </template>
      <template #createTime="scope">
        <span>{{ parseTime(scope.row.createTime) }}</span>
      </template>
    </myTableSearch>

    <!-- 添加或修改机构对话框 -->
    <myDialog :isDialog="open" :title="title" :width="'620px'" @handleClose="cancel">
      <template slot="content">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24" v-if="form.parentId !== 0">
              <el-form-item label="上级机构" prop="parentId">
                <treeselect :disabled="treeselectDisabled" v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级机构"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="机构名称" prop="deptName">
                <el-input v-model="form.deptName" placeholder="请输入机构名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序" prop="sort">
                <el-input-number v-model="form.sort" controls-position="right" :min="1"/>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactName">
                <el-input v-model="form.contactName" placeholder="请输入联系人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
              </el-form-item>
            </el-col>
          </el-row> -->
  <!--        <el-row>-->
  <!--          <el-col :span="12">-->
  <!--            <el-form-item label="机构等级" prop="level">-->
  <!--              <el-select v-model="form.level" placeholder="请选择">-->
  <!--                <el-option-->
  <!--                    v-for="item in levelData"-->
  <!--                    :key="item.key"-->
  <!--                    :label="item.name"-->
  <!--                    :value="item.key"-->
  <!--                    :disabled="item.disabled"-->
  <!--                >-->
  <!--                </el-option>-->
  <!--              </el-select>-->
  <!--            </el-form-item>-->
  <!--          </el-col>-->
  <!--        </el-row>-->
        </el-form>
      </template>
      <template slot="footer">
        <div class="formBtnBox">
          <div class="saveBtn" @click="submitForm">确 定</div>
          <div class="editBtn ml-4"  @click="cancel">取 消</div>
        </div>
      </template>
    </myDialog>
  </div>
</template>

<script>
import {deptTree, deptDetail, deptAdd, deptUpdate, deptDelete, deptListExclude} from "@/api/sys/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {uploadFile} from "@/api/upload/upload.js";
export default {
  name: "Dept",
  components: {Treeselect},
  data() {
    return {
      formData: [
        {
          label: "机构名称",
          type: "input",
          key: "deptName",
        },
      ],
      tableLabel: [
        {
          prop: "deptName",
          label: "机构名称",
        },
        {
          prop: "sort",
          label: "排序",
        },
        // {
        //   prop: "contactName",
        //   label: "联系人",
        // },
        // {
        //   prop: "contactPhone",
        //   label: "联系电话",
        // },
        {
          prop: "createTime",
          label: "创建时间",
        },
      ],

      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 机构树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级机构不能为空", trigger: "blur"}
        ],
        deptName: [
          {required: true, message: "机构名称不能为空", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "显示排序不能为空", trigger: "blur"}
        ],
        // contactName: [
        //   {required: true, message: "联系人不能为空", trigger: "blur"}
        // ],
        // contactPhone: [
        //   {required: true, message: "联系电话不能为空", trigger: "blur"}
        // ],
        // level: [
        //   {required: true, message: "请选择等级", trigger: "blur"}
        // ],
      },
      treeselectDisabled:false,
      // levelData:[
      //   {key:"1",name:"8指",disabled:false},
      //   {key:"2",name:"组织部",disabled:false},
      //   {key:"3",name:"话务组",disabled:false},
      // ]
    };
  },
  created() {
    // this.getList();
  },
  methods: {
    getList(e) {
      return deptTree(e)
    },
    //格式化搜索字段
    recombinationData(param, callback) {
      let params = {
        recombinationDataType:'queryParams',
        deptName:param.deptName
      }
      callback(params);
    },
    successQuery(e,callback){
      this.deptList = this.handleTree(e, "id");
      callback(this.deptList)
    },
    // logo
    logUpload({file}) {
      const that = this;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "app-logo");
      uploadFile(formData).then((res) => {
        if (res.code === 200) {
          that.form.logoUrl = res.data.url;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/jpg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG JPEG PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    /** 转换机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        deptName: undefined,
        sort: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.open = true;
      this.title = "添加机构";
      deptTree({}).then(response => {
        this.deptOptions = [];
        const dept = { id: "0", deptName: '主类目', children: [] };
        dept.children = this.handleTree(response.data, "id");
        this.deptOptions.push(dept);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.treeselectDisabled = false;
      deptDetail(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改机构";
      });
      deptListExclude(row.id).then(response => {
        this.deptOptions = [];
        const dept = { id: "0", deptName: '主类目', children: [] };
        dept.children = this.handleTree(response.data, "id");
        this.deptOptions.push(dept);
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            deptUpdate(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
              this.$refs.myTableSearchRef.searchReset();
            });
          } else {
            deptAdd(this.form).then(() => {
              this.msgSuccess("新增成功");
              this.open = false;
              // this.getList();
              this.$refs.myTableSearchRef.searchReset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return deptDelete(row.id);
      }).then(() => {
        // this.getList();
        this.$refs.myTableSearchRef.searchReset();
        this.msgSuccess("删除成功");
      })
    }
  }
};
</script>
<style  scoped>
/deep/ .el-upload {
  border: none;
}

/deep/ .el-form-item-content, .el-cascader {
  width: 330px;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 146px;
  height: 146px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  line-height: 146px;
  text-align: center;
}

.bgitem {
  display: flex;
  flex-wrap: wrap;

.item {
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  align-items: center;
  margin-right: 5px;
  cursor: pointer;

img {
  width: 146px;
  height: 146px;
}
}
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: fill;
}

.el-select {
  width: 100%;
}

.el-date-editor.el-input {
  width: 100% !important;
}
</style>
